package com.famnote.getitbeauty;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.famnote.getitbeauty.R;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;


public class RegNickNameActivity extends Activity implements OnClickListener
{
	// Debugging
    private static final String TAG = "RegNickNameActivity";
    private static final boolean D = true;
    
	private Activity activity;
	
	private Handler mHandler = new Handler();
	
	private ProgressDialog dialog;
	
	
    
 // Variable Declaration should be in onCreate()
 private Button mSubmit;
 
 private EditText mNicknameEditText;

 private String mNickname;
 
 //protected DBHelper DB = new DBHelper(Registration.this); 
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_reg_nick_name);
  
  activity = this;
  
  //Assignment of UI fields to the variables
  mSubmit = (Button)findViewById(R.id.submit);
  mSubmit.setOnClickListener(this);
  
  
  mNicknameEditText = (EditText)findViewById(R.id.enickname);
  
 }

 
 public void onClick(View v) 
 {
  
  switch(v.getId()){
  
  /*
  case R.id.cancel:
   Intent i = new Intent(getBaseContext(), LoginActivity.class);
   startActivity(i);
   //finish();
   break;
   */
  
  case R.id.submit:
   
   
   mNickname = mNicknameEditText.getText().toString();
   
   
   boolean invalid = false;
      
   if(mNickname.equals(""))
   {
    invalid = true;
    Toast.makeText(getApplicationContext(), getResources().getString(R.string.notice_nickname), Toast.LENGTH_SHORT).show();
   }
   /*
   else
   if(roomSubtitle.equals(""))
   {
    invalid = true;
    Toast.makeText(getApplicationContext(), getResources().getString(R.string.notice_room_subtitle), Toast.LENGTH_SHORT).show();
   }
   */
   else
      
	if(invalid == false)
      {
    	  
		String msg = getResources().getString(R.string.registering_profile);	
        dialog = ProgressDialog.show(this, "", msg, true);
        
		try {
			/*
			String androidid = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
			String url = "http://push.appaas.com/hulbox/of_reg_nickname.php?deviceid=" + androidid 
				+ "&nickname=" + URLEncoder.encode(mNickname, "utf-8");
				*/
			
			TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
			String deviceid = tm.getDeviceId();
			String url = "http://push.appaas.com/hulbox/rc_reg_nickname.php?deviceid=" + deviceid 
					+ "&nickname=" + URLEncoder.encode(mNickname, "utf-8");
			
			RegNickNameTask regNickNameTask = new RegNickNameTask();
			regNickNameTask.execute(url);
		}catch(Exception e){
        	Log.d("reg nick name",e.toString());
        }   
		
       //addEntry(fname, lname, Gen, uname, pass, email);
       //Intent i_register = new Intent(this, LoginActivity.class);
       //startActivity(i_register);
       //finish();
       
    	  /*
    	  finish();
          
    	  
            Intent intent = new Intent(this, GroupChat.class);
        	
    		//String room = mProfileid + "@conference.push.appaas.com";
    		//i.putExtra("room", room);
    		
            intent.putExtra("title", roomTitle);
    		
            intent.putExtra("subtitle", roomSubtitle);
    		
    		//String nickName = "hithere";
    		
    		//intent.putExtra("nickname", nickName);
     
    		startActivity(intent);
    	  */
    	  
    	  
    	  
      }
      
      break;
      }
    }
 


 
 
 public void onDestroy()
 {
  super.onDestroy();
  ///DB.close();
 }
 
 
 
	/** AsyncTask to download xml data */
 	private class RegNickNameTask extends AsyncTask<String, Integer, String>{
     String data = null;
             
     @Override
     protected String doInBackground(String... url) {
                     try{
                         data = downloadUrl(url[0]);
                             
                     }catch(Exception e){
                     	Log.d("Background Task",e.toString());
                     }
                     if(D) Log.e(TAG, "result: " + data);
                     
                     return data;
     }

     @Override
     protected void onPostExecute(String result) {
             	
          dialog.dismiss();
             	
          if (data.trim().equals("OK")) {

        	  finish();
        	  
        	  //Intent i = new Intent(activity, MainActivity.class);
        	  //i.putExtra("nickname", mNickname);
        	  //startActivity(i);
         		
          } else {
         	 
        	  Toast.makeText(getApplicationContext(), getResources().getString(R.string.notice_reg_nickname_fail), Toast.LENGTH_SHORT).show();
 			
          }
             	
     }
 	}
	
	
	/** A method to download xml data from url */
 	private String downloadUrl(String strUrl) throws IOException{
     String data = "";
     InputStream iStream = null;
     try{
             URL url = new URL(strUrl);
             
             // Creating an http connection to communicate with url 
             HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

             // Connecting to url 
             urlConnection.connect();

             // Reading data from url 
             iStream = urlConnection.getInputStream();
             
             BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
             
             StringBuffer sb  = new StringBuffer();
             
             String line = "";
             while( ( line = br.readLine())  != null){
             	sb.append(line);
             }
             
             
             data = sb.toString();

             br.close();

     }catch(Exception e){
             Log.d("Exception while downloading url", e.toString());
             if(D) Log.e(TAG, e.toString());
     }finally{
             iStream.close();
     }

     return data;
 	}

 
}
